package models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

import com.feth.play.module.pa.user.AuthUser;

import play.db.ebean.Model;

@Entity
@Table(name = "accounts")
public class Account extends Model {
	
	private static final long serialVersionUID = 1L;
	
	@Column(name = "id")
	@GeneratedValue(generator = "SEQ_TABLE", strategy = GenerationType.TABLE)
	@Id
	@TableGenerator(name = "SEQ_TABLE")
	private long id;
	
	@Column(name = "provider_key")
	private String providerKey;
	
	@Column(name = "provider_user_id")
	private String providerUserId;
	
	@Column(name = "user")
	@ManyToOne(fetch = FetchType.LAZY)
	private User user;

	public static final Finder<Long, Account> find = new Finder<Long, Account>(long.class, Account.class);

	public long getId() {
		return id;
	}

	public String getProviderKey() {
		return providerKey;
	}

	public void setProviderKey(String providerKey) {
		this.providerKey = providerKey;
	}

	public String getProviderUserId() {
		return providerUserId;
	}

	public void setProviderUserId(String providerUserId) {
		this.providerUserId = providerUserId;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void update(final AuthUser authUser) {
		this.providerKey = authUser.getProvider();
		this.providerUserId = authUser.getId();
	}

	public static Account create(final AuthUser authUser) {
		final Account account = new Account();
		account.update(authUser);
		return account;
	}

	public static Account create(final Account account) {
		final Account newAccount = new Account();
		newAccount.providerKey = account.providerKey;
		newAccount.providerUserId = account.providerUserId;
		return newAccount;
	}

	public static Account findByProviderKey(final User user, final String key) {
		return find.where().eq("user", user).eq("providerKey", key).findUnique();
	}
}
